import React, { FC, ReactNode, memo, useEffect, useState } from 'react'
import {
  NavBar,
  List,
  TextArea,
  Button,
  Picker,
  CalendarPicker,
  Toast,
  Modal
} from 'antd-mobile'
import { RightOutline } from 'antd-mobile-icons'
import dayjs from 'dayjs'
import ic_server from '@/assets/images/ic_server.png'
import MyCreateOrder from './style'
import { useLocation, useNavigate } from 'react-router-dom'
import qs from 'qs'
import { toDataURL } from 'qrcode'
import { useAppDispatch, useAppSelector } from '@/store'
import { fetchGetDoctorList } from './store'
import { submitOrderApi } from './api'

interface Iprops {
  children?: ReactNode
}

const CreateOrder: FC<Iprops> = () => {
  const dispatch = useAppDispatch()
  const {
    createOrder: { companion, hospitals }
  } = useAppSelector((state) => ({
    createOrder: state.createOrder
  }))

  const [currentStep, setCurrentStep] = useState(0)
  const steps = ['填写订单', '在线支付', '专人服务', '服务完成']

  const { search } = useLocation()
  const obj = qs.parse(search.slice(1))

  // 状态
  const [hospitalVisible, setHospitalVisible] = useState(false)
  const [doctorVisible, setDoctorVisible] = useState(false)
  const [calendarVisible, setCalendarVisible] = useState(false)
  const [visitDate, setVisitDate] = useState<Date>()

  //
  const [hospitalId, setHospitalId] = useState((Number(obj.id) as number) || 0)
  const [doctorId, setDoctorId] = useState(0)

  //
  const [hospital, setHospital] = useState<string>(
    (obj.hName as string) || '请选择就诊医院'
  )
  const [doctor, setDoctor] = useState<string>('请选择陪诊师')
  const [address, setAddress] = useState('')
  const [phone, setPhone] = useState('')
  const [request, setRequest] = useState('')
  const [dateStr, setDateStr] = useState(0)
  const [codeImage, setCodeImage] = useState('')

  const handleSubmit = async () => {
    const info = {
      hospital_id: hospitalId,
      hospital_name: hospital,
      companion_id: doctorId,
      receiveAddress: address,
      tel: phone,
      demand: request,
      starttime: dateStr
    }
    const hasEmpty = Object.values(info).some(
      (value) => value === '' || value === 0 || value === undefined
    )
    const phoneReg = /^1\d{10}$/
    if (hasEmpty) {
      Toast.show({
        content: '请填写完整信息'
      })
      return
    }
    if (!phoneReg.test(info.tel)) {
      Toast.show({
        content: '请输入正确的手机号'
      })
      return
    }
    const {
      data: { wx_code }
    } = await submitOrderApi(info)
    setCurrentStep(1)
    const code = await toDataURL(wx_code)
    console.log(code)
    setCodeImage(code)

    // Toast.show({
    //   content: '提交成功！'
    // })

    setShowModal(true)
  }
  const navigate = useNavigate()
  const back = () => {
    navigate(-1)
  }
  useEffect(() => {
    dispatch(fetchGetDoctorList())

    const script = document.createElement('script')
    script.src =
      'https://lf-cdn.coze.cn/obj/unpkg/flow-platform/chat-app-sdk/1.2.0-beta.10/libs/cn/index.js'
    script.async = true
    script.onload = () => {
      console.log('✅ Coze SDK 加载完成')

      // 2️⃣ 初始化 WebChatClient

      const client = new window.CozeWebSDK.WebChatClient({
        config: {
          bot_id: '7561420672098926638' // ✅ 换成你自己的 bot_id
        },
        componentProps: {
          title: '智能分诊助手' // 聊天窗口标题
        },
        auth: {
          type: 'token',
          token:
            'pat_3uyfvzpqxeQPLWrc3ojpOo0N23zbjcNcMamdX87Jdq86xvXukblmCid0DTjWpAzw', // ✅ 你的 token
          onRefreshToken: function () {
            return 'pat_3uyfvzpqxeQPLWrc3ojpOo0N23zbjcNcMamdX87Jdq86xvXukblmCid0DTjWpAzw' // ✅ token 过期时重新获取逻辑（简单写死）
          }
        },
        ui: {
          base: {
            layout: 'mobile'
          }
        }
      })

      console.log('✅ Coze WebChatClient 初始化完成', client)
    }

    document.body.appendChild(script)

    return () => {
      document.body.removeChild(script)
    }
  }, [])
  const [isShowModal, setShowModal] = useState(false)
  return (
    <MyCreateOrder>
      <div className="service-order">
        <NavBar onBack={back}>填写服务订单</NavBar>

        {/* 顶部进度条 */}
        <div className="progress-bar">
          <div className="line-bg">
            <div
              className="line-fill"
              style={{ width: `${(currentStep / (steps.length - 1)) * 100}%` }}
            ></div>
          </div>
          <div className="step-list">
            {steps.map((step, index) => (
              <div
                key={step}
                className={`step-item ${index <= currentStep ? 'active' : ''}`}
                onClick={() => setCurrentStep(index)}
              >
                <div className="circle">{index + 1}</div>
                <div className="label">{step}</div>
              </div>
            ))}
          </div>
        </div>

        {/* 内容区 */}
        <div className="content-area">
          <div className="card">
            <div className="service-header">
              <img src={ic_server} alt="服务图标" className="service-img" />
              <div className="service-info">
                <div className="service-title">就医陪诊（尊享）</div>
              </div>
            </div>

            <List className="form-list">
              <List.Item
                extra={hospital}
                arrow={<RightOutline />}
                onClick={() => setHospitalVisible(true)}
              >
                <span>*</span>就诊医院
              </List.Item>
              <List.Item
                extra={
                  visitDate
                    ? dayjs(visitDate).format('YYYY-MM-DD')
                    : '请选择就诊时间'
                }
                arrow={<RightOutline />}
                onClick={() => setCalendarVisible(true)}
              >
                <span>*</span>就诊时间
              </List.Item>

              <List.Item
                extra={doctor}
                arrow={<RightOutline />}
                onClick={() => setDoctorVisible(true)}
              >
                <span>*</span>陪诊师
              </List.Item>
              <List.Item>
                <span>*</span>接送地址
                <input
                  placeholder="请输入接送人地址"
                  value={address}
                  onChange={(e) => setAddress(e.target.value)}
                />
              </List.Item>
              <List.Item>
                <span>*</span>联系电话
                <input
                  placeholder="请输入联系电话"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                />
              </List.Item>
            </List>
          </div>

          <div className="text-area-wrapper">
            <div className="label">
              <span>*</span>服务需求
            </div>
            <TextArea
              placeholder="请简单描述您要就诊的科室,不清楚什么科室点击右边悬浮窗试试"
              autoSize={{ minRows: 3 }}
              value={request}
              onChange={setRequest}
            />
          </div>

          <div className="submit-btn">
            <Button color="primary" block onClick={handleSubmit}>
              提交订单
            </Button>
          </div>
        </div>

        {/* Picker + Calendar 组件 */}
        <Picker
          // defaultValue={}
          columns={hospitals}
          visible={hospitalVisible}
          onClose={() => setHospitalVisible(false)}
          onConfirm={(v, extend) => {
            setHospitalId(extend.items[0]?.key as number)
            setHospital(v[0] as string)
          }}
        />
        <Picker
          columns={companion}
          visible={doctorVisible}
          onClose={() => setDoctorVisible(false)}
          onConfirm={(v, extend) => {
            setDoctorId(Number(extend.items[0]?.key) as number)
            setDoctor(v[0] as string)
          }}
        />

        <CalendarPicker
          closeOnMaskClick
          visible={calendarVisible}
          selectionMode="single"
          defaultValue={visitDate}
          onClose={() => setCalendarVisible(false)}
          onConfirm={(val) => {
            setVisitDate(val as Date)
            setCalendarVisible(false)
            Toast.show({
              content: '已选择 ' + dayjs(val).format('YYYY-MM-DD')
            })
            setDateStr(new Date(dayjs(val).format('YYYY-MM-DD')).getTime())
          }}
        />

        {/* 蒙版 */}
        <Modal
          visible={isShowModal}
          content={
            <div style={{ textAlign: 'center' }}>
              <img
                src={codeImage}
                alt="二维码"
                style={{ width: '150px', margin: '10px 0' }}
              />
              <p>请使用温馨扫描二维码</p>
            </div>
          }
          closeOnAction
          onClose={() => {
            setShowModal(false)
          }}
          actions={[
            {
              key: 'confirm',
              text: '支付完成'
            }
          ]}
          onAction={() => {
            setShowModal(false)
            Toast.show({ content: '一秒后自动跳转订单页' })
            setTimeout(() => {
              navigate('/pz/order')
            }, 1000)
          }}
        />
      </div>
    </MyCreateOrder>
  )
}

export default memo(CreateOrder)
